﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace OrganizationName.Factory.LifeTimeContracts
{
    public class IntervalLifeTimeContract : ILifeTimeContract
    {
        private Stopwatch _Stopwatch;
        private object _Instance;
        private TimeSpan _Delta;

        public IntervalLifeTimeContract(TimeSpan delta)
        {
            _Delta = delta;
        }

        public bool IsValid
        {
            get
            {
                return _Stopwatch != null && _Stopwatch.Elapsed.TotalMilliseconds < _Delta.TotalMilliseconds;
            }
        }

        public object Instance
        {
            get
            {
                return _Instance;
            }
            set
            {
                lock (this)
                {
                    _Instance = value;
                    _Stopwatch = Stopwatch.StartNew();
                }
            }
        }

        public object SyncRoot
        {
            get
            {
                return this;
            }
        }
    }
}
